// internal/dao/user_dao.go
package dao

import (
	"strings"

	"gorm.io/gorm"

	"github.com/jfastfiler/internal/model"
)

type UserDAO struct {
	db *gorm.DB
}

func NewUserDAO(database *Database) *UserDAO {
	return &UserDAO{db: database.db}
}

func (dao *UserDAO) Create(user *model.User) error {
	return dao.db.Create(user).Error
}

func (dao *UserDAO) GetByID(id int) (*model.User, error) {
	var user model.User
	err := dao.db.First(&user, id).Error
	return &user, err
}

func (dao *UserDAO) GetByUsername(username string) (*model.User, error) {
	var user model.User
	err := dao.db.Where("username = ?", username).First(&user).Error
	return &user, err
}

func (dao *UserDAO) GetByEmail(email string) (*model.User, error) {
	var user model.User
	err := dao.db.Where("email = ?", email).First(&user).Error
	return &user, err
}

func (dao *UserDAO) Update(user *model.User) error {
	return dao.db.Save(user).Error
}

func (dao *UserDAO) UpdateStatus(id int, status int) error {
	return dao.db.Model(&model.User{}).Where("id = ?", id).Update("status", status).Error
}

func (dao *UserDAO) Delete(id int) error {
	return dao.db.Delete(&model.User{}, id).Error
}

func (dao *UserDAO) List(params *UserQueryParams) ([]model.User, int64, error) {
	var users []model.User
	var total int64

	query := dao.db.Model(&model.User{})
	
	if params.Username != "" {
		query = query.Where("username LIKE ?", "%"+params.Username+"%")
	}
	if params.Email != "" {
		query = query.Where("email LIKE ?", "%"+params.Email+"%")
	}
	if params.Role != "" {
		query = query.Where("role = ?", params.Role)
	}
	if params.Status >= 0 {
		query = query.Where("status = ?", params.Status)
	}
	if params.Department != "" {
		query = query.Where("department LIKE ?", "%"+params.Department+"%")
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页
	offset := (params.Page - 1) * params.PageSize
	query = query.Offset(offset).Limit(params.PageSize)

	// 排序
	if params.Sort != "" {
		order := params.Sort
		if strings.ToUpper(params.Order) == "DESC" {
			order += " DESC"
		} else {
			order += " ASC"
		}
		query = query.Order(order)
	} else {
		query = query.Order("id DESC")
	}

	err := query.Find(&users).Error
	return users, total, err
}

func (dao *UserDAO) UpdateLoginInfo(id int, ip string) error {
	return dao.db.Model(&model.User{}).Where("id = ?", id).Updates(map[string]interface{}{
		"last_login":  gorm.Expr("CURRENT_TIMESTAMP"),
		"last_ip":     ip,
		"login_count": gorm.Expr("login_count + 1"),
	}).Error
}

func (dao *UserDAO) GetStatistics() (*UserStatistics, error) {
	var stats UserStatistics
	
	err := dao.db.Model(&model.User{}).Select(
		"COUNT(*) as total_users",
		"SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as active_users",
		"SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as inactive_users",
		"SUM(CASE WHEN role = 'admin' THEN 1 ELSE 0 END) as admin_users",
	).Scan(&stats).Error

	if err != nil {
		return nil, err
	}

	return &stats, nil
}

type UserQueryParams struct {
	Username   string
	Email      string
	Role       string
	Status     int
	Department string
	Page       int
	PageSize   int
	Sort       string
	Order      string
}

type UserStatistics struct {
	TotalUsers    int64 `json:"total_users"`
	ActiveUsers   int64 `json:"active_users"`
	InactiveUsers int64 `json:"inactive_users"`
	AdminUsers    int64 `json:"admin_users"`
}